package com.jgc.stage02.同步工具类;

import java.util.concurrent.CountDownLatch;

/**
 * Created by Administrator on 2022/2/11.
 * CountDownLatch是一个计数器，在它的构造方法中需要指定一个值，用来设定计数的次数。
 每调用一次countDown()方法，数值便会减一，CountDownLatch会一直阻塞着调用await()方法的线程，直到计数器的值变为0
 */
public class TestCountDownLatch {


    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(2);
        System.out.println("初始latch的数量" + latch.getCount());
        new Thread(() ->{
            try {
                System.out.println("子线程" + Thread.currentThread().getName()+"开始执行");
                Thread.sleep(3000);
                System.out.println("子线程" + Thread.currentThread().getName()+"执行结束");
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() ->{
            try {
                System.out.println("子线程" + Thread.currentThread().getName()+"开始执行");
                Thread.sleep(3000);
                System.out.println("子线程" + Thread.currentThread().getName()+"执行结束");
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        try {
            System.out.println("等待2个子线程执行完毕...");
            latch.await();
            System.out.println("latch的数量" + latch.getCount());
            System.out.println("2个子线程执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
